<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{number}}.{{title}}</title>
    <!-- 引入ACE插件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/extlanguage_tools.js" type="text/javascript" charset="utf-8"></script>
    <!-- 引入jquery CDN -->
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        .container .navbar {
            width: 100%;
            height: 50px;
            background-color: black;
            overflow: hidden;
        }

        .container .navbar a {
            display: inline-block;
            width: 80px;
            color: white;
            font-size: large;
            line-height: 50px;
            text-decoration: none;
            text-align: center;
        }

        .container .navbar a:hover {
            background-color: green;
        }

        .container .navbar .login {
            float: right;
        }

        .container .navbar .user-area {
            float: right;
            display: flex;
            align-items: center;
        }

        .container .navbar .username {
            color: white;
            font-size: large;
            line-height: 50px;
            text-align: center;
            padding: 0 10px;
            margin-right: 10px;
        }

        .container .part1 {
            width: 100%;
            height: 600px;
            overflow: hidden;
        }

        .container .part1 .left_desc {
            width: 50%;
            height: 600px;
            float: left;
            overflow: scroll;
        }

        .container .part1 .left_desc h3 {
            padding-top: 10px;
            padding-left: 10px;
        }

        .container .part1 .left_desc pre {
            padding-top: 10px;
            padding-left: 10px;
            font-size: medium;
            font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS',
                sans-serif;
        }

        .container .part1 .right_code {
            width: 50%;
            float: right;
        }

        .container .part1 .right_code .ace_editor {
            height: 600px;
        }

        .container .part2 {
            width: 100%;
            overflow: hidden;
        }

        .container .part2 .result {
            width: 300px;
            float: left;
        }

        .container .part2 .btn-submit {
            width: 120px;
            height: 50px;
            font-size: large;
            float: right;
            background-color: #26bb9c;
            color: #FFF;
            border: 0px;
            margin-top: 10px;
            margin-right: 10px;
            cursor: pointer;
        }

        .container .part2 button:hover {
            background-color: #1ea086;
        }

        .container .part2 .result {
            margin-top: 15px;
            margin-left: 15px;
        }

        .container .part2 .result pre {
            font-size: large;
        }

        /* 成功提示样式 */
        .success-message {
            color: #4CAF50;
            font-weight: bold;
        }

        .error-message {
            color: #f44336;
            font-weight: bold;
        }

        .next-question-notice {
            color: #2196F3;
            margin-top: 10px;
        }

        /* 倒计时进度条样式 */
        .countdown-bar {
            height: 5px;
            background-color: #e0e0e0;
            width: 300px;
            margin-top: 10px;
            overflow: hidden;
            border-radius: 3px;
        }

        .countdown-progress {
            height: 100%;
            background-color: #2196F3;
            width: 100%;
            transition: width 1s linear;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 导航栏 -->
        <div class="navbar">
            <a href="/">首页</a>
            <a href="/all_questions">题库</a>
            <a href="#">竞赛</a>
            <a href="#">讨论</a>
            <a href="#">求职</a>
            
            <!-- 未登录状态 -->
            <div class="user-area" id="notLoginArea">
                <a class="login" href="/login">登录</a>
                <a class="register" href="/register">注册</a>
            </div>
            
            <!-- 已登录状态 (默认隐藏) -->
            <div class="user-area" id="loginArea" style="display: none;">
                <span class="username" id="usernameDisplay"></span>
                <a href="javascript:;" id="logoutBtn">退出</a>
            </div>
        </div>
        
        <!-- 题目描述和代码编辑区 -->
        <div class="part1">
            <div class="left_desc">
                <h3><span id="number">{{number}}</span>.{{title}}_{{star}}</h3>
                <pre>{{desc}}</pre>
            </div>
            <div class="right_code">
                <pre id="code" class="ace_editor"><textarea class="ace_textinput">{{pre_code}}</textarea></pre>
            </div>
        </div>
        
        <!-- 提交区域和结果展示 -->
        <div class="part2">
            <div class="result"></div>
            <button class="btn-submit" onclick="submit()">提交代码</button>
        </div>
    </div>
    
    <script>
        // 初始化ACE编辑器
        editor = ace.edit("code");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/c_cpp");
        editor.setFontSize(16);
        editor.getSession().setTabSize(4);
        editor.setReadOnly(false);
        
        // 启用提示菜单
        ace.require("ace/ext/language_tools");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        
        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
            // 绑定退出登录事件
            document.getElementById('logoutBtn').addEventListener('click', handleLogout);
        };
        
        // 检查登录状态
        function checkLoginStatus() {
            fetch('/api/check_login')
                .then(res => res.text())
                .then(username => {
                    if (username !== 'not_login' && username.trim() !== '') {
                        // 登录状态：显示昵称和退出按钮
                        document.getElementById('notLoginArea').style.display = 'none';
                        document.getElementById('loginArea').style.display = 'block';
                        document.getElementById('usernameDisplay').textContent = username;
                    } else {
                        // 未登录状态：显示登录和注册按钮
                        document.getElementById('notLoginArea').style.display = 'block';
                        document.getElementById('loginArea').style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('检查登录状态失败:', error);
                });
        }
        
        // 处理退出登录（退出后返回主页）
        function handleLogout() {
            fetch('/api/logout')
                .then(() => {
                    // 退出成功后跳转到主页
                    window.location.href = '/';
                })
                .catch(error => {
                    console.error('退出登录失败:', error);
                });
        }
        
        // 提交代码
        function submit() {
            // 收集数据
            var code = editor.getSession().getValue();
            var number = document.getElementById("number").textContent;
            var judge_url = "/judge/" + number;
            
            // 发送请求
            $.ajax({
                method: 'Post',
                url: judge_url,
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify({
                    'code': code,
                    'input': ''
                }),
                success: function (data) {
                    show_result(data, number);
                }
            });
        }
        
        // 显示结果并处理自动跳转下一题
        function show_result(data, currentNumber) {
            var result_div = $(".container .part2 .result");
            result_div.empty();
            
            var _status = data.status;
            var _reason = data.reason;
            
            // 显示结果状态
            var reason_lable = $("<p>", {
                text: _reason,
                class: _status === "Accepted" ? "success-message" : "error-message"
            });
            reason_lable.appendTo(result_div);
            
            // 如果答案正确，自动跳转下一题
            if (_status === "Accepted") {
                // 显示跳转提示
                var notice = $("<p>", {
                    class: "next-question-notice",
                    text: "答案正确，正在获取下一题..."
                });
                notice.appendTo(result_div);
                
                // 请求下一题编号
                $.get("/api/next?current=" + currentNumber, function(nextNumber) {
                    if (nextNumber && nextNumber !== "" && nextNumber !== currentNumber) {
                        // 添加倒计时进度条
                        var countdownBar = $("<div>", {class: "countdown-bar"});
                        var progressBar = $("<div>", {class: "countdown-progress"});
                        countdownBar.append(progressBar);
                        result_div.append(countdownBar);
                        
                        // 3秒倒计时并更新进度条
                        let seconds = 3;
                        const interval = setInterval(() => {
                            seconds--;
                            notice.text(`即将跳转到下一题... (${seconds}秒后)`);
                            progressBar.css("width", (seconds / 3) * 100 + "%");
                            
                            if (seconds <= 0) {
                                clearInterval(interval);
                                // 跳转到下一题
                                window.location.href = "/question?number=" + nextNumber;
                            }
                        }, 1000);
                    } else {
                        // 没有下一题
                        notice.text("恭喜！您已完成所有题目！");
                        // 添加返回题库按钮
                        var backBtn = $("<button>", {
                            text: "返回题库",
                            class: "btn-submit",
                            style: "float: none; margin-top: 10px"
                        }).click(function() {
                            window.location.href = "/all_questions";
                        });
                        result_div.append(backBtn);
                    }
                }).fail(function() {
                    notice.text("获取下一题失败，请手动选择题目。");
                    // 添加返回题库按钮
                    var backBtn = $("<button>", {
                        text: "返回题库",
                        class: "btn-submit",
                        style: "float: none; margin-top: 10px"
                    }).click(function() {
                        window.location.href = "/all_questions";
                    });
                    result_div.append(backBtn);
                });
            } 
            // 显示其他结果信息
            else if (_status === 0) {
                var _stdout = data.stdout;
                var _stderr = data.stderr;
                
                if (_stdout) {
                    var stdout_lable = $("<pre>", {
                        text: "输出: " + _stdout
                    });
                    stdout_lable.appendTo(result_div);
                }
                
                if (_stderr) {
                    var stderr_lable = $("<pre>", {
                        text: "错误: " + _stderr,
                        class: "error-message"
                    });
                    stderr_lable.appendTo(result_div);
                }
            }
        }
    </script>
</body>

</html>
